package com.sansecy.customview.imageview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 给定宽度和高度，自动适配高度或宽度以保证能完整显示下加载的图片
 */
public class AutoSizeImageView extends ImageView {
    public AutoSizeImageView(Context context) {
        super(context);
    }

    public AutoSizeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoSizeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getDrawable() != null) {
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.EXACTLY) {
                //给定高度，适配宽度
                Drawable drawable = getDrawable();
                int intrinsicWidth = drawable.getIntrinsicWidth();
                int intrinsicHeight = drawable.getIntrinsicHeight();

                int heightSize = MeasureSpec.getSize(heightMeasureSpec);
                float targetWidth = intrinsicWidth / (float) intrinsicHeight * heightSize;
                //向上取整，保证视图可以显示下内容
                setMeasuredDimension((int) (targetWidth + 0.5), heightSize);
            } else if (heightMode == MeasureSpec.AT_MOST && widthMode == MeasureSpec.EXACTLY) {
                //给定宽度，适配高度
                Drawable drawable = getDrawable();
                int intrinsicWidth = drawable.getIntrinsicWidth();
                int intrinsicHeight = drawable.getIntrinsicHeight();

                int widthSize = MeasureSpec.getSize(widthMeasureSpec);
                float targetHeight = intrinsicHeight / (float) intrinsicWidth * widthSize;
                //向上取整，保证视图可以显示下内容
                setMeasuredDimension(widthSize, (int) (targetHeight + 0.5));
            }
        }
        //非以上两种模式，由super处理
    }

}
